package com.chenbei.erp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.erp.domain.Customer;
import com.chenbei.erp.vo.req.CustomerReq;
import com.chenbei.erp.mapper.CustomerMapper;
import com.chenbei.erp.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomerService extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    private final Object lock = new Object();

    @Override
    public void add(Customer customer) {
        synchronized (lock) {
            LambdaQueryWrapper<Customer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Customer::getPhone, customer.getPhone());
            if (count(lambdaQueryWrapper) > 0) {
                throw new LogicHandleException("客户已存在");
            }
            customer.setCode(buildCode());
            customer.setStatus(1);
            customer.setCreateTime(LocalDateTime.now());
            save(customer);
        }
    }

    @Override
    public void update(Customer customer) {
        LambdaQueryWrapper<Customer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Customer::getId, customer.getId())
                .eq(Customer::getPhone, customer.getPhone());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("手机号已存在");
        }
        customer.setUpdateTime(LocalDateTime.now());
        updateById(customer);
    }

    @Override
    public Page<Customer> pageList(CustomerReq req) {
        Page<Customer> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return baseMapper.pageList(pageConfig, req);
    }

    private String buildCode() {
        String prefix = "CUST";
        String categoryCode = "00";
//        String extraCode = "0000";        //额外码（预留字段）
        long count = count() + 1;
        String serialNumber = String.format("%04d", count);
        return String.join("-", Arrays.asList(prefix, categoryCode, serialNumber));
    }
}
